/*
 * @Copyright (C), 2021 - 2030, ShenZhen Benew Technology Co.,Ltd.
 * @author: benew-android
 * @date: 3/12/21 4:10 PM
 * @describe:
 */
package com.benew.ntt.xseval.utils

import java.lang.StringBuilder

/**
 * 韵母转化工具类
 * 例如：“天才”的拼音：tiān cái -> tian1 cai2
 */
object RhymeUtils {
    var rhyme = arrayOf(
        charArrayOf('a', 'ā', 'á', 'ǎ', 'à'),
        charArrayOf('o', 'ō', 'ó', 'ǒ', 'ò'),
        charArrayOf('e', 'ē', 'é', 'ě', 'è'),
        charArrayOf('i', 'ī', 'í', 'ǐ', 'ì'),
        charArrayOf('u', 'ū', 'ú', 'ǔ', 'ù'),
        charArrayOf('v', 'ǖ', 'ǘ', 'ǚ', 'ǜ')
    )

    /**
     * 文本韵母转换
     *
     * @param text 原文本
     * @return 转换后文本
     */
    fun covertRhyme(text: String?): String? {
        if (text != null && text.isNotEmpty()) {
            val chars = text.toCharArray()
            val number = IntArray(1)
            val newText = StringBuilder()
            for (aChar in chars) {
                replaceChar(aChar, newText, number)
            }
            if (number[0] != 0) { //如果还有数字就拼接到最后面
                newText.append(number[0])
            }
            return newText.toString()
        }
        return text
    }

    /**
     * @param c       字符
     * @param newText 新文本
     * @param number  存放声调的数组
     */
    private fun replaceChar(c: Char, newText: StringBuilder, number: IntArray) {
        for (chars in rhyme) {
            for (z in 1 until chars.size) {
                if (c == chars[z]) {
                    number[0] = z
                    newText.append(chars[0])
                    return
                }
            }
        }
        if (!Character.isLetter(c) && number[0] != 0) { //如果非字母类型和还有数字
            newText.append(number[0])
            number[0] = 0
        }
        newText.append(c)
    }

    /**
     * 文本拼接拼音
     *
     * @param text 原文本
     * @return 转换后文本
     */
    fun textMergeSpell(text: String?, spellText: String?): String? {
        if (text != null && text.isNotEmpty() && spellText != null && spellText.isNotEmpty()) {
            val textChars = text.toCharArray()
            val spellTextArray = spellText.split(" ").toTypedArray()
            val newText = StringBuilder()
            val length = spellTextArray.size
            for ((index, textChar) in textChars.withIndex()) {
                newText.append(textChar)
                if (index < length) {
                    newText.append("(").append(spellTextArray[index]).append(")")
                }
            }
            return newText.toString()
        }
        return text
    }
}